package com.api.gbhg.zengping.web;

import com.alibaba.fastjson.JSON;
import com.api.gbhg.zengping.common.res.Res;
import com.api.gbhg.zengping.dao.PropertyManagementCostDao;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;

import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: gbhg-oa
 * @description: 经费来源扣减
 * @author: Mr.zeng
 * @create: 2021-02-19 14:05
 **/
public class MoneyDeductedAction {

    public static final Logger LOGGER = LoggerFactory.getLogger("gbhg");
    private   final PropertyManagementCostDao pmc=new PropertyManagementCostDao();
    /**
     * 扣减预算来源(上年结转、当年预算)
     * @param map
     * @return
     */
    @POST
    @Path("/modifyDeductionAmount")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String DeductionAmount(Map<String,String>[] map){
        Map<String,String> res=new HashMap<>();
        boolean flag=false;
        for (int i = 0; i < map.length; i++) {
            Object requestId = map[i].get("lcjlid");
            Double amount = Double.valueOf(map[i].get("money"));
            amount/=10000;
            //扣上年结转
            amount=koujian(requestId,"上年结转核批",amount);
            if(amount<=0){
                flag=true;
                continue;
            }
            //扣当年预算
            amount=koujian(requestId,"当年预算核批",amount);
            if(amount<=0){
                flag=true;
                continue;
            }
        }
        if(flag){
            res.put("msg","ok");
            return JSON.toJSONString(res);
        }
        res.put("msg","error");
        return JSON.toJSONString(res);
    }

    /**
     * 扣减
     * @param requestId  流程id
     * @param yslylx    预算来源类型
     * @param amount    报销金额
     * @return
     */
    public Double koujian(Object requestId,String yslylx,Double amount){
        RecordSet rs=new RecordSet();
        String sql="select sum(syed)syed,lylx from uf_jingfeilaiyuan where lcid="+requestId+" and yslylx='"+yslylx+"' group by lylx order by lylx";
            rs.executeQuery(sql);
            while (rs.next()){
                double syed = rs.getDouble("syed");
                int lylx = rs.getInt("lylx");
                if (amount<=0){
                    return amount;
                }
                double max = Math.max(amount, syed);
                if(max==amount){
                    // 报销金额大于等于剩余额度
                    if(amount>=syed){
                        amount-=syed;
                        // 扣减明细
                        String updateSql="update uf_jingfeilaiyuan set syed=0 where lcid="+requestId+" and lylx="+lylx+" and yslylx='"+yslylx+"'";
                        RecordSetTrans rst=new RecordSetTrans();
                        rst.setAutoCommit(false);
                        try {
                            rst.executeUpdate(updateSql);
                        } catch (Exception e) {
                            e.printStackTrace();
                            rst.rollback();
                        }
                        rst.commit();
                    }
                }else {
                    // 剩余额度大于 报销金额
                    syed-=amount;
                    amount=0.0;
                    // 扣减明细
                    String updateSql="update uf_jingfeilaiyuan set syed="+syed+" where lcid="+requestId+" and lylx="+lylx+" and yslylx='"+yslylx+"'";
                    RecordSetTrans rst=new RecordSetTrans();
                    rst.setAutoCommit(false);
                    try {
                        rst.executeUpdate(updateSql);
                    } catch (Exception e) {
                        e.printStackTrace();
                        rst.rollback();
                    }
                    rst.commit();
                    return amount;
                }
            }
            return amount;
    }

    /**
     * 报销=退回 时，减去扣减金额，剩余额度加
     * 预算来源+
     * @param map
     * @return
     */
    @POST
    @Path("/returnDeductionAmount")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    public String returnDeductionAmount(Map<String,String>[] map){
        RecordSetTrans rst=new RecordSetTrans();
        rst.setAutoCommit(false);
        for (int i = 0; i < map.length; i++) {
            String lcjlid = map[i].get("lcjlid");
            String bmjjzcfl = map[i].get("bmjjzcfl");
            BigDecimal moneyDj = new BigDecimal(map[i].get("moneyDj"));
            BigDecimal dj2 = new BigDecimal(0.00);
            boolean b = pmc.modifyFreezeMoney(lcjlid, bmjjzcfl, moneyDj,dj2, true);
            if(!b){
                return JSON.toJSONString(Res.error(502,"程序出现错误"));
            }
            // 预算来源剩余额度增加
            String querySql="select je,syed,yslylx,lylx,id from uf_jingfeilaiyuan where lcid="+lcjlid+"  order by  lylx desc";
            try {
                rst.executeQuery(querySql);
                StringBuffer sb=new StringBuffer();
                while (rst.next()){
                    BigDecimal je = new BigDecimal(rst.getDouble("je"));
                    BigDecimal syed = new BigDecimal(rst.getDouble("syed"));
                    int id = rst.getInt("id");
                    if(je==syed){
                        continue;
                    }
                    if(moneyDj.compareTo(je)==1||moneyDj.compareTo(je)==0){
                        moneyDj=moneyDj.subtract(je);
                        String modifySql="update uf_jingfeilaiyuan set syed+="+syed+" where lcid="+lcjlid+" and id="+id+";";
                        sb.append(modifySql);
                    }
                }
                rst.executeUpdate(sb.toString());
            } catch (Exception e) {
                e.printStackTrace();
                rst.rollback();
                return JSON.toJSONString(Res.ok(500,"退回出现错误"));
            }
        }
        rst.commit();
        return JSON.toJSONString(Res.ok(200,"成功"));
    }
}
